package br.com.emanuelvictor.architectureandroid.app1.repository;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeSet;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import br.com.emanuelvictor.architectureandroid.app1.entity.Daily;
import br.com.emanuelvictor.architectureandroid.app1.entity.Point;
import br.com.emanuelvictor.architectureandroid.app1.support.DatabaseHelper;

@SuppressLint("SimpleDateFormat")
public class PointRepository {
	protected DatabaseHelper database;
	protected String[] columns = { "id", "date" };

	public PointRepository(DatabaseHelper database) {
		this.database = database;
	}

	public void insert(Point point) {
		database.getWritableDatabase().insert("Ponto", null,
				point.toContentValues());
	}

	public void update(Point point) {
		database.getWritableDatabase().update("Ponto", point.toContentValues(),
				"id = ?", new String[] { point.id.toString() });
	}

	public void remove(Point point) {
		database.getWritableDatabase().delete("Ponto", "id = ?",
				new String[] { point.id.toString() });
	}

	// public List<Point> findAll() {
	// ArrayList<Point> points = new ArrayList<Point>();
	//
	// Cursor cursor = database.getReadableDatabase().query("Ponto", columns,
	// null, null, null, null, "id DESC");
	//
	// while (cursor.moveToNext()) {
	// Log.d("", "Lendo point" + cursor.getString(1));
	// Point p = new Point(cursor.getLong(0), cursor.getString(1));
	// points.add(p);
	// }
	// cursor.close();
	// return points;
	// }

	// public List<Point> findAllToday() {
	// ArrayList<Point> points = new ArrayList<Point>();
	//
	// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	//
	// Cursor cursor = database.getReadableDatabase().query("Ponto", columns,
	// "date(date) = ?", new
	// String[]{df.format(Calendar.getInstance().getTime())}, null, null,
	// "id ASC", null);
	//
	// while (cursor.moveToNext()) {
	// Log.d("", "Lendo point" + cursor.getString(1));
	// Point p = new Point(cursor.getLong(0), cursor.getString(1));
	// points.add(p);
	// }
	// cursor.close();
	// return points;
	// }
	//

	// public List<Daily> findAllPoints() {
	// ArrayList<Daily> daily = new ArrayList<Daily>();
	// LinkedHashMap<String, ArrayList<Point>> pointsAgrupados = new
	// LinkedHashMap<String, ArrayList<Point>>();
	//
	// Cursor cursor = database.getReadableDatabase().query("Ponto", columns,
	// null, null, null, null, "id ASC");
	//
	// while (cursor.moveToNext()) {
	// Point p = new Point(cursor.getLong(0), cursor.getString(1));
	//
	// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	// String stringDate = df.format(p.date.getTime());
	// if (!pointsAgrupados.containsKey(stringDate))
	// pointsAgrupados.put(stringDate, new ArrayList<Point>());
	//
	// pointsAgrupados.get(stringDate).add(p);
	// }
	// cursor.close();
	//
	// TreeSet<String> keys = new TreeSet<String>(pointsAgrupados.keySet());
	// Iterator<String> iterator = keys.descendingIterator();
	//
	// while (iterator.hasNext()) {
	// String date = iterator.next();
	// Daily p = new Daily();
	// p.setPoints(pointsAgrupados.get(date));
	// daily.add(p);
	// }
	// return daily;
	// }

	// public void insertAll(List<Point> points) throws Exception {
	// SQLiteDatabase db = database.getWritableDatabase();
	// db.beginTransaction();
	// try {
	// for (Point point: points) {
	// db.insertOrThrow("Ponto", null, point.toContentValues());
	// }
	// db.setTransactionSuccessful();
	// } finally {
	// db.endTransaction();
	// }
	//
	// }

	public void updateAll(List<Point> points/* , boolean deleteActual */)
			throws Exception {
		SQLiteDatabase db = database.getWritableDatabase();

		db.beginTransaction();
		try {
			db.delete("Ponto", null, null);

			for (Point point : points) {
				db.insertOrThrow("Ponto", null, point.toContentValues());
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	public List<Point> findAllByDate(Calendar calendar) {
		ArrayList<Point> points = new ArrayList<Point>();

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Cursor cursor;
		if (calendar == null) {
			cursor = database.getReadableDatabase().query("Ponto", columns,
					null, null, null, null, "id DESC");
		} else {
			cursor = database.getReadableDatabase().query("Ponto", columns,
					"date(date) = ?",
					new String[] { df.format(calendar.getTime()) }, null, null,
					"id ASC", null);
		}

		Log.d("", "Lendo ponto pela data ");

		while (cursor.moveToNext()) {

			Point p = new Point(cursor.getLong(0), cursor.getString(1));
			points.add(p);

		}
		cursor.close();
		return points;
	}
	
	// Utilizar somente esse método para pesquisar todos
	public List<Daily> findDaily() {

		// Pega todos os pontos
		ArrayList<Daily> daily = new ArrayList<Daily>();
		LinkedHashMap<String, ArrayList<Point>> pointsAgrupados = new LinkedHashMap<String, ArrayList<Point>>();

		Cursor cursor = database.getReadableDatabase().query("Ponto", columns,
				null, null, null, null, "id ASC");

		while (cursor.moveToNext()) {
			Point p = new Point(cursor.getLong(0), cursor.getString(1));

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String stringDate = df.format(p.date.getTime());
			if (!pointsAgrupados.containsKey(stringDate))
				pointsAgrupados.put(stringDate, new ArrayList<Point>());

			pointsAgrupados.get(stringDate).add(p);
		}
		cursor.close();

		TreeSet<String> keys = new TreeSet<String>(pointsAgrupados.keySet());
		Iterator<String> iterator = keys.descendingIterator();

		while (iterator.hasNext()) {
			String date = iterator.next();
			Daily p = new Daily();
			p.setPoints(pointsAgrupados.get(date));
			daily.add(p);
		}
		return daily;
	}

}